package com.tgy.crud.controller;

import com.tgy.crud.domain.Person;
import com.tgy.crud.domain.User;
import com.tgy.crud.service.CrudService;
import com.tgy.crud.service.SendMessageService;
import com.tgy.crud.utils.Const;
import com.tgy.crud.utils.RandomUtil;
import com.tgy.crud.utils.Util;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;
import java.util.List;

@Slf4j
@ToString
@Controller
//@SessionAttributes(names = {"name"},types = Person.class)
public class CrudController {


    @Autowired
    private CrudService crudService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private SendMessageService sendMessageService;

    @ModelAttribute
    public void addPerson(@RequestParam(value = "id",required = false) Integer id, Model model){

        if (id != null){

            Person person = crudService.findPersonById(id);

          //  log.info(person.toString());
            if (person != null){

                model.addAttribute("person",person);
            }
        }
    }

    @PostMapping("/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Boolean remember_me,
                        Model model, HttpServletRequest request, HttpServletResponse response){


        System.out.println("remember_me: " + remember_me);

        System.out.println(username + " : " + password);

        if (StringUtils.isEmpty(username)){

            model.addAttribute("error","用户名不能为空");
            return "login";
        }else  if (StringUtils.isEmpty(password)){

            model.addAttribute("error","密码不能为空");
            return "login";
        }

        if (!username.equals("zhangsan") || !password.equals("123456")){

            model.addAttribute("error","用户名密码错误");
            return "login";
        }

        HttpSession session = request.getSession();

        User user = new User(username, password);
        final String jsessionId = RandomUtil.randomUUID();
        redisTemplate.opsForValue().set(Util.getJessionId(Const.REDISUSERID,jsessionId),user, Duration.ofHours(1));

        Cookie cookie = new Cookie(Const.JSESSIONID, jsessionId);
        cookie.setPath("/");

        if (remember_me != null && remember_me){

            cookie.setMaxAge(60 * 60);
        }else {
            cookie.setMaxAge(-1);
        }

        // 上面的设置MaxAge要在添加到response之前才能生效
        response.addCookie(cookie);
        model.addAttribute("user",user);

        // 发送消息队列
        sendMessageService.sendAMQPMessage("login","login",user);

        return "redirect:index";
    }

    @GetMapping("/logout")
    public String loginOut(HttpServletRequest request,HttpSession session, HttpServletResponse response){

        Cookie cookie = Util.getCookie(request, "JSESSIONID");

        if (cookie != null){

            final String jsessionId = cookie.getValue();
            if (!StringUtils.isEmpty(jsessionId)){

                redisTemplate.delete(Util.getJessionId(Const.REDISUSERID,jsessionId));
                cookie.setMaxAge(0);
                response.addCookie(cookie);
            }
        }


        return "redirect:/tologin";
    }


    @GetMapping("/tables.html")
    public String toTables(Model model){

        List<Person> allPersons = crudService.findAllPersons();
        model.addAttribute("persons",allPersons);

        return "tables";
    }

    @DeleteMapping("/person/{id}")
    public String deletePerson(@PathVariable("id") Integer id){

        if (id != null){

            crudService.deletePerson(id);
        }

        return "redirect:/tables.html";
    }

    @PostMapping("/person")
    public String addPerson(Person person){

        crudService.insertPerson(person);
        return "redirect:/tables.html";
    }

    @PutMapping("/person")
    public String updatePerson(@ModelAttribute("person01") Person person,Model model){


        Object person1 = model.getAttribute("person");

        crudService.updatePerson(person);
        return "redirect:/tables.html";
    }

    @GetMapping({"/topersonupdate.html/{id}","/topersonupdate.html"})
    public String toPersonUpdate(@PathVariable(value = "id",required = false) Integer id,Model model){

        if (id != null){

            model.addAttribute("person", crudService.findPersonById(id));
        }
        return "update";
    }



    @GetMapping("/test")
    @ResponseBody
    public User test(@Valid @Validated User user, BindingResult bindingResult){


        if (bindingResult != null){

            List<ObjectError> allErrors = bindingResult.getAllErrors();

            for (ObjectError allError : allErrors) {

                log.info(allError.getDefaultMessage());
            }
        }

        return user;
    }

    @InitBinder
    public void initWebDataBinder(WebDataBinder webDataBinder, HttpServletRequest request){

        /**
         * 格式化从页面请求的string到date
         */
        webDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
    }



}
